package com.enba.boot.security.jwt;

import cn.hutool.core.convert.Convert;
import com.enba.boot.security.properties.SecurityJwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JwtTokenUtils {

  private final SecurityJwtProperties jwtProperties;

  public JwtTokenUtils(SecurityJwtProperties jwtProperties) {
    this.jwtProperties = jwtProperties;
  }

  /**
   * 生成令牌
   *
   * @param claims 数据声明
   * @return 令牌
   */
  public String generateToken(Map<String, Object> claims) {
    String jwt =
        Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
            .compact();
    return jwtProperties.getTokenPrefix() + " " + jwt;
  }

  /**
   * 从令牌中获取数据声明
   *
   * @param token 令牌
   * @return 数据声明
   */
  public Claims parseToken(String token) {
    return Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody();
  }

  /**
   * 根据声明 获取值
   *
   * @param claims 声明
   * @param key 建
   * @return 值
   */
  private static String getValue(Claims claims, String key) {
    return Convert.toStr(claims.get(key), "");
  }
}
